#include "api.h"
#include "dish.h"
#include "dishrecommend.h"
#include <QDebug>
#include <QFile>
#include <QMessageBox>
Api::Api(QObject *parent) : QObject(parent)
{
    connect(accessManager,&QNetworkAccessManager::finished, this,&Api::finishedSlot,Qt::UniqueConnection);

}


void Api::getRecommendDish(){
    QNetworkRequest request;
    request.setUrl(QUrl(getRecommendDishUrl));//设置url
    request.setRawHeader("Authorization",token.toLatin1());
    accessManager->get(request);//发送GET请求
}

void Api::infoCer(){
    qDebug()<<"获取冰箱信息";
    QNetworkRequest request;
    request.setUrl(QUrl(infoCerUrl));//设置url
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setRawHeader("Authorization",token.toLatin1());

    QFile aFile(cerPath);
    if (!aFile.exists()) //文件不存在
    {
        QMessageBox::critical(0 , "证书警告" , "找不到冰箱证书，请联系客服!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(0 , "证书警告" , "证书读取失败，请重试", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    QJsonObject json;
    QString filter = QString::fromUtf8(aFile.readAll());
    json.insert("filter",filter);
    aFile.close();
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    accessManager->post(request, postData);//发送POST请求
}
void Api::downloadCoreData(){
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");//构建json头
    request.setRawHeader("Authorization",token.toLatin1());
    qDebug()<<"添加token"<<token;
    request.setUrl(QUrl(downloadCoreDataUrl));
    accessManager->get(request);
}
void Api::getUserInfo()
{
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");//构建json头
    request.setRawHeader("Authorization",token.toLatin1());
    qDebug()<<"添加token"<<token;
    request.setUrl(QUrl(userInfoUrl));
    accessManager->get(request);
}
/**
 * @brief Api::loginByPassword 成功发出信号loginByPasswordSuccess
 * @param phone
 * @param password
 */
void Api::loginByPassword(QString phone,QString password)
{
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");//构建json头
    QJsonObject json;
    json.insert("phone",phone);
    json.insert("password",password);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    request.setUrl(QUrl(loginByPasswordUrl));//设置url
    accessManager->post(request, postData);//发送POST请求
}

void Api::searchDish(QString keyword,int size,int index){
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");//构建json头
    request.setUrl(QUrl(searchDishUrl));//设置url
    QJsonObject json,filter;
    filter.insert("name",keyword);
    json.insert("filter",filter);
    json.insert("index",index);
    json.insert("size",size);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    accessManager->post(request,postData);
}
void Api::coverFromServer(){
    qDebug()<<"获取冰箱信息";
    QNetworkRequest request;
    request.setUrl(QUrl(coverFromServerUrl));//设置url
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setRawHeader("Authorization",token.toLatin1());

    QFile aFile(cerPath);
    if (!aFile.exists()) //文件不存在
    {
        QMessageBox::critical(0 , "证书警告" , "找不到冰箱证书，请联系客服!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(0 , "证书警告" , "证书读取失败，请重试", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    QJsonObject json;
    QString filter = QString::fromUtf8(aFile.readAll());
    json.insert("filter",filter);
    aFile.close();
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    accessManager->post(request, postData);//发送POST请求

}
void Api::coverByTerminal(){
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");//构建json头
    request.setRawHeader("Authorization",token.toLatin1());
    request.setUrl(QUrl(coverByTerminalUrl));//设置url
    QJsonObject json;
    SQL sql;
    QList<Food> foods = sql.foodUserData();
    QList<Remind> reminds = sql.remindUserData();
    QList<Storage> storages = sql.storageUserData();
    QJsonArray foodarray;
    QJsonObject foodobj;
    for(int i=0;i<foods.size();i++)
    {
        foodobj.insert("createUser",(int)foods[i].create_user);
        foodobj.insert("createId",(int)foods[i].create_id);
        foodobj.insert("alias",foods[i].alias);
        foodobj.insert("info",foods[i].info);
        foodobj.insert("name",foods[i].name);
        foodobj.insert("pic",foods[i].pic);
        foodobj.insert("shelfLife",foods[i].shelf_time);
        foodobj.insert("type",foods[i].type);
        foodobj.insert("unit",foods[i].unit);
        foodarray.append(foodobj);
    }

    QJsonArray storagearray;
    QJsonObject storageobj;
    for(int i=0;i<storages.size();i++)
    {
        storageobj.insert("amount",storages[i].amount);
        storageobj.insert("foodId",(int)storages[i].food_id);
        storageobj.insert("fridgeId",0);
        storageobj.insert("userId",(int)storages[i].user_id);
        storagearray.append(storageobj);
    }

    QJsonArray rmindarray;
    QJsonObject rmindobj;
    for(int i=0;i<reminds.size();i++)
    {
        rmindobj.insert("amount",reminds[i].amount);
        rmindobj.insert("date",reminds[i].date.toString("yyyy-MM-dd"));
        rmindobj.insert("foodId",(int)reminds[i].food_id);
        rmindobj.insert("fridgeId",0);
        rmindobj.insert("id",(int)reminds[i].id);
        rmindobj.insert("userId",(int)reminds[i].user_id);
        rmindarray.append(rmindobj);
    }


    QFile aFile(cerPath);
    if (!aFile.exists()) //文件不存在
    {
        QMessageBox::critical(0 , "证书警告" , "找不到冰箱证书，请联系客服!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(0 , "证书警告" , "证书读取失败，请重试", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }

    QString cer = QString::fromUtf8(aFile.readAll());
    aFile.close();

    json.insert("fridgeCer",cer);
    json.insert("foodList",foodarray);
    json.insert("fridgeStorageList",storagearray);
    json.insert("remindList",rmindarray);


    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    accessManager->post(request,postData);
}
void Api::isDirty(){
    qDebug()<<"获取冰箱信息";
    QNetworkRequest request;
    request.setUrl(QUrl(isDirtyUrl));//设置url
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setRawHeader("Authorization",token.toLatin1());

    QFile aFile(cerPath);
    if (!aFile.exists()) //文件不存在
    {
        QMessageBox::critical(0 , "证书警告" , "找不到冰箱证书，请联系客服!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(0 , "证书警告" , "证书读取失败，请重试", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    QJsonObject json;
    QString filter = QString::fromUtf8(aFile.readAll());
    json.insert("filter",filter);
    aFile.close();
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    accessManager->post(request, postData);//发送POST请求
}
void Api::bind(QString password){
    QNetworkRequest request;
    request.setUrl(QUrl(bindUrl));//设置url
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setRawHeader("Authorization",token.toLatin1());
    QJsonObject json;
    QFile aFile(cerPath);
    if (!aFile.exists()) //文件不存在
    {
        QMessageBox::critical(0 , "证书警告" , "找不到冰箱证书，请联系客服!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(0 , "证书警告" , "证书读取失败，请重试", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
        return;
    }
    QString cer = QString::fromUtf8(aFile.readAll());
    json.insert("cer",cer);
    json.insert("password",password);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    QByteArray postData = jsonDocument.toJson(QJsonDocument::Compact);
    accessManager->post(request,postData);
}

void Api::finishedSlot(QNetworkReply* reply)
{
    // 没有错误
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(bytes, &jsonError);  // 转化为 JSON 文档
        QJsonObject object = doucment.object();
        int code = 0;
        if (object.contains("code"))
        {
            QJsonValue value = object.value("code");  // 获取指定 key 对应的 value
            code=value.toInt();
            qDebug()<<code;
            qDebug()<<successCode;
            if(code == successCode)
            {
                if (reply->url().toString() == loginByPasswordUrl)
                {
                    processLoginByPassword(object);
                }
                else if(reply->url().toString() == userInfoUrl)
                {
                    processUserInfo(object);
                }
                else if(reply->url().toString() == getRecommendDishUrl)
                {
                    processGetRecommendDish(object);
                }
                else if(reply->url().toString() == searchDishUrl)
                {
                    processSearchDish(object);
                }
                else if(reply->url().toString() == infoCerUrl)
                {
                    processInfoCer(object);
                }
                else if(reply->url().toString() == coverFromServerUrl)
                {
                    processCoverFromServer(object);
                }
                else if(reply->url().toString() == downloadCoreDataUrl)
                {
                    processDownloadCoreData(object);
                }
                else if(reply->url().toString() == coverByTerminalUrl)
                {
                    processCoverByTerminal(object);
                }
                else if(reply->url().toString() == isDirtyUrl)
                {
                    processIsDirty(object);
                }
                else if(reply->url().toString() == bindUrl)
                {
                    processBind(object);
                }
            }
            else if (code == 23000)
            {
                emit tokenTimeoutSignal();
                QMessageBox::critical(0 , "Token失效" , "Token已过期，请重新登录!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
            }
            else{
                if(object.contains("message"))
                {
                    QString s = object.value("message").toString();
                    QMessageBox::critical(0 , "请求异常" , s, QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
                }
                else{
                    QMessageBox::critical(0 , "服务器异常" , "服务器异常，请联系管理员!", QMessageBox::Ok | QMessageBox::Default , 0 , 	0 );
                }

            }
        }
    }
    else
    {
        processFailed(reply);
    }
    reply->deleteLater();
}
void Api::processGetRecommendDish(QJsonObject reply){
    QList<DishRecommend>* result = new QList<DishRecommend>;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        if(value.isArray())
        {
            QJsonArray array = value.toArray();
            int nSize = array.size();
            for(int i=0;i<nSize;i++)
            {
                DishRecommend recommend;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("name"))
                {
                    QJsonValue value = qobject.value("name");
                    recommend.typeName=value.toString();
                }
                if(qobject.contains("dishes"))
                {
                     QJsonValue value = qobject.value("dishes");
                     QJsonArray array1 = value.toArray();
                     int nSize1 = array1.size();
                     QList<Dish>* dishList = new QList<Dish>;
                     for(int j=0;j<nSize1;j++)
                     {
                         Dish dish;
                         QJsonValue value = array1.at(j);
                         QJsonObject qobject = value.toObject();
                         if(qobject.contains("id"))
                         {
                              QJsonValue value = qobject.value("id");
                              dish.id=value.toInt();
                         }
                         if(qobject.contains("name"))
                         {
                              QJsonValue value = qobject.value("name");
                              dish.name=value.toString();
                         }
                         if(qobject.contains("material"))
                         {
                              QJsonValue value = qobject.value("material");
                              dish.material=value.toString();
                         }
                         if(qobject.contains("detail"))
                         {
                              QJsonValue value = qobject.value("detail");
                              dish.detail=value.toString();
                         }
                         if(qobject.contains("pic"))
                         {
                              QJsonValue value = qobject.value("pic");
                              dish.pic=value.toString();
                         }
                         if(qobject.contains("type"))
                         {
                              QJsonValue value = qobject.value("type");
                              dish.type=value.toString();
                         }
                         if(qobject.contains("userId"))
                         {
                              QJsonValue value = qobject.value("userId");
                              dish.userId=value.toInt();
                         }
                         if(qobject.contains("likeCount"))
                         {
                              QJsonValue value = qobject.value("likeCount");
                              dish.likeCount=value.toInt();
                         }
                         if(qobject.contains("commentCount"))
                         {
                              QJsonValue value = qobject.value("commentCount");
                              dish.commentCount=value.toInt();
                         }
                         dishList->append(dish);
                     }
                     recommend.dishList = dishList;
                     result->append(recommend);
                }
            }
        }
    }
    emit getRecommendDishSuccess(result);
}
void Api::processBind(QJsonObject reply){
    emit bindSuccess();
}
void Api::processUserInfo(QJsonObject reply){
    qDebug()<<"接收到查询返回报文";
    qDebug()<<reply;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        if(value.isObject())
        {
            QJsonObject obj = value.toObject();

            QString username;
            if(obj.contains("username"))
            {
                QJsonValue value = obj.value("username");
                username=value.toString();
            }

            QString phone;
            if(obj.contains("phone"))
            {
                QJsonValue value = obj.value("phone");
                phone=value.toString();
            }


            QString email;
            if(obj.contains("email"))
            {
                QJsonValue value = obj.value("email");
                email=value.toString();
            }

            int gender;
            if(obj.contains("gender"))
            {
                QJsonValue value = obj.value("gender");
                gender=value.toInt();
            }

            QString avatar;
            if(obj.contains("avatar"))
            {
                QJsonValue value = obj.value("avatar");
                avatar=value.toString();
            }
            int id;
            if(obj.contains("id"))
            {
                QJsonValue value = obj.value("id");
                id=value.toInt();
            }
            emit getUserInfoSuccess(id,username,phone,email,avatar,gender);
        }
    }

}
void Api::processLoginByPassword(QJsonObject reply){
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        if(value.isObject())
        {
            QJsonObject obj = value.toObject();
            if(obj.contains("token"))
            {
                QJsonValue value = obj.value("token");
                token=value.toString();
                qDebug()<<"获取到token"<<token;
            }
        }
        emit loginByPasswordSuccess(token);
    }
}
void Api::processSearchDish(QJsonObject reply){
    qDebug()<<"接收到查询返回报文";
    QList<Dish>* dishList = new QList<Dish>;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        QJsonObject qobject = value.toObject();
        //这里对于rows的处理与上面菜谱推荐对于dishes的处理是相同的
        if(qobject.contains("rows"))
        {
            QJsonValue value = qobject.value("rows");
            QJsonArray array1 = value.toArray();
            int nSize1 = array1.size();
            for(int j=0;j<nSize1;j++)
            {
                Dish dish;
                QJsonValue value = array1.at(j);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("id"))
                {
                     QJsonValue value = qobject.value("id");
                     dish.id=value.toInt();
                }
                if(qobject.contains("name"))
                {
                     QJsonValue value = qobject.value("name");
                     dish.name=value.toString();
                }
                if(qobject.contains("material"))
                {
                     QJsonValue value = qobject.value("material");
                     dish.material=value.toString();
                }
                if(qobject.contains("detail"))
                {
                     QJsonValue value = qobject.value("detail");
                     dish.detail=value.toString();
                }
                if(qobject.contains("pic"))
                {
                     QJsonValue value = qobject.value("pic");
                     dish.pic=value.toString();
                }
                if(qobject.contains("type"))
                {
                     QJsonValue value = qobject.value("type");
                     dish.type=value.toString();
                }
                if(qobject.contains("userId"))
                {
                     QJsonValue value = qobject.value("userId");
                     dish.userId=value.toInt();
                }
                if(qobject.contains("likeCount"))
                {
                     QJsonValue value = qobject.value("likeCount");
                     dish.likeCount=value.toInt();
                }
                if(qobject.contains("commentCount"))
                {
                     QJsonValue value = qobject.value("commentCount");
                     dish.commentCount=value.toInt();
                }
                dishList->append(dish);
            }
        }
    }
    emit searchDishSuccess(dishList);
}
void Api::processInfoCer(QJsonObject reply){
    qDebug()<<"接收到查询返回报文"<<reply;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        if(value.isObject())
        {
            QJsonObject obj = value.toObject();
            if(obj.contains("id"))
            {
                QJsonValue value = obj.value("id");
                fridge.id=value.toInt();
            }
            if(obj.contains("name"))
            {
                QJsonValue value = obj.value("name");
                fridge.name=value.toString();
            }
            if(obj.contains("createTime"))
            {
                QJsonValue value = obj.value("createTime");
                QString s = value.toString();
                fridge.createTime = QDateTime::fromString(s,"yyyy-MM-dd");

            }
            if(obj.contains("activeTime"))
            {
                QJsonValue value = obj.value("activeTime");
                QString s = value.toString();
                fridge.activeTime = QDateTime::fromString(s,"yyyy-MM-dd");
            }
            if(obj.contains("guarantee"))
            {
                QJsonValue value = obj.value("guarantee");
                fridge.guarantee=value.toInt();
            }
            if(obj.contains("userId"))
            {
                QJsonValue value = obj.value("userId");
                fridge.userId = value.toInt();
            }
            if(obj.contains("activeCode"))
            {
                QJsonValue value = obj.value("activeCode");
                fridge.activeCode = value.toString();
            }
            emit infoCerSuccess(fridge);
        }
    }
}
void Api::processCoverFromServer(QJsonObject reply){
    qDebug()<<"接收到查询返回报文，进入从服务器下载处理函数";
//    qDebug()<<reply;
    QList<Food> foods;
    QList<Storage> storages;
    QList<Remind> reminds;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        QJsonObject qobject = value.toObject();
        if(qobject.contains("foodList"))
        {
            QJsonArray array = qobject.value("foodList").toArray();
            for(int i=0;i<array.size();i++)
            {
                Food food;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("createUser"))
                {
                    QJsonValue value = qobject.value("createUser");
                    food.create_user = value.toInt();
                }
                if(qobject.contains("createId"))
                {
                    QJsonValue value = qobject.value("createId");
                    food.create_id = value.toInt();
                }
                if(qobject.contains("name"))
                {
                    QJsonValue value = qobject.value("name");
                    food.name = value.toString();
                }
                if(qobject.contains("type"))
                {
                    QJsonValue value = qobject.value("type");
                    food.type = value.toInt();
                }
                if(qobject.contains("shelfLife"))
                {
                    QJsonValue value = qobject.value("shelfLife");
                    food.shelf_time = value.toInt();
                }
                if(qobject.contains("unit"))
                {
                    QJsonValue value = qobject.value("unit");
                    food.unit = value.toInt();
                }
                if(qobject.contains("info"))
                {
                    QJsonValue value = qobject.value("info");
                    food.info = value.toString();
                }
                if(qobject.contains("alias"))
                {
                    QJsonValue value = qobject.value("alias");
                    food.alias = value.toString();
                }
                if(qobject.contains("pic"))
                {
                    QJsonValue value = qobject.value("pic");
                    food.pic = value.toString();
                }
                foods.append(food);
            }
        }
        if(qobject.contains("fridgeStorageList"))
        {
            QJsonArray array = qobject.value("fridgeStorageList").toArray();
            for(int i=0;i<array.size();i++)
            {
                Storage storage;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("userId"))
                {
                    QJsonValue value = qobject.value("userId");
                    storage.user_id = value.toInt();
                }
                if(qobject.contains("foodId"))
                {
                    QJsonValue value = qobject.value("foodId");
                    storage.food_id = value.toInt();
                }
                if(qobject.contains("amount"))
                {
                    QJsonValue value = qobject.value("amount");
                    storage.amount = value.toInt();
                }
                storages.append(storage);
            }
        }
        if(qobject.contains("remindList"))
        {
            QJsonArray array = qobject.value("remindList").toArray();
            for(int i=0;i<array.size();i++)
            {
                Remind remind;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("userId"))
                {
                    QJsonValue value = qobject.value("userId");
                    remind.user_id = value.toInt();
                }
                if(qobject.contains("foodId"))
                {
                    QJsonValue value = qobject.value("foodId");
                    remind.food_id = value.toInt();
                }
                if(qobject.contains("amount"))
                {
                    QJsonValue value = qobject.value("amount");
                    remind.amount = value.toInt();
                }
                if(qobject.contains("id"))
                {
                    QJsonValue value = qobject.value("id");
                    remind.id = value.toInt();
                }
                if(qobject.contains("date"))
                {
                    QJsonValue value = qobject.value("date");
                    remind.date = QDate::fromString(value.toString(),"yyyy-MM-dd");
                }
                reminds.append(remind);
            }
        }
    }
    SQL sql;
    sql.foodClearUserData();
    sql.remindClearUserData();
    sql.storageClearUserData();
    sql.foodAdd(foods);
    sql.remindAdd(reminds);
    sql.storageAdd(storages);
    emit coverFromServerSuccess();
}
void Api::processDownloadCoreData(QJsonObject reply){
    QList<Food> foods;
    QList<Unit> units;
    QList<FoodType> foodTypes;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        QJsonObject qobject = value.toObject();
        if(qobject.contains("foodList"))
        {
            QJsonArray array = qobject.value("foodList").toArray();
            for(int i=0;i<array.size();i++)
            {
                Food food;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("createUser"))
                {
                    QJsonValue value = qobject.value("createUser");
                    food.create_user = value.toInt();
                }
                if(qobject.contains("createId"))
                {
                    QJsonValue value = qobject.value("createId");
                    food.create_id = value.toInt();
                }
                if(qobject.contains("name"))
                {
                    QJsonValue value = qobject.value("name");
                    food.name = value.toString();
                }
                if(qobject.contains("type"))
                {
                    QJsonValue value = qobject.value("type");
                    food.type = value.toInt();
                }
                if(qobject.contains("shelfLife"))
                {
                    QJsonValue value = qobject.value("shelfLife");
                    food.shelf_time = value.toInt();
                }
                if(qobject.contains("unit"))
                {
                    QJsonValue value = qobject.value("unit");
                    food.unit = value.toInt();
                }
                if(qobject.contains("info"))
                {
                    QJsonValue value = qobject.value("info");
                    food.info = value.toString();
                }
                if(qobject.contains("alias"))
                {
                    QJsonValue value = qobject.value("alias");
                    food.alias = value.toString();
                }
                if(qobject.contains("pic"))
                {
                    QJsonValue value = qobject.value("pic");
                    food.pic = value.toString();
                }
                foods.append(food);
            }
        }
        if(qobject.contains("unitList"))
        {
            QJsonArray array = qobject.value("unitList").toArray();
            for(int i=0;i<array.size();i++)
            {
                Unit unit;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("id"))
                {
                    QJsonValue value = qobject.value("id");
                    unit.id = value.toInt();
                }
                if(qobject.contains("name"))
                {
                    QJsonValue value = qobject.value("name");
                    unit.name = value.toString();
                }
                units.append(unit);
            }
        }
        if(qobject.contains("foodTypeList"))
        {
            QJsonArray array = qobject.value("foodTypeList").toArray();
            for(int i=0;i<array.size();i++)
            {
                FoodType foodtype;
                QJsonValue value = array.at(i);
                QJsonObject qobject = value.toObject();
                if(qobject.contains("id"))
                {
                    QJsonValue value = qobject.value("id");
                    foodtype.id = value.toInt();
                }
                if(qobject.contains("name"))
                {
                    QJsonValue value = qobject.value("name");
                    foodtype.name = value.toString();
                }
                if(qobject.contains("pic"))
                {
                    QJsonValue value = qobject.value("pic");
                    foodtype.pic = value.toString();
                }
                foodTypes.append(foodtype);
            }
        }
    }
    SQL sql;
    sql.foodtypeClearCoreData();
    sql.foodClearCoreData();
    sql.unitClearCoreData();
    sql.foodAdd(foods);
    sql.foodtypeAdd(foodTypes);
    sql.unitAdd(units);
    emit downloadCoreDataSuccess();
}
void Api::processCoverByTerminal(QJsonObject reply){
    qDebug()<<"接收到查询返回报文"<<reply;
    emit coverByTerminalSuccess();
}
void Api::processIsDirty(QJsonObject reply){
    qDebug()<<"接收到查询返回报文"<<reply;
    if(reply.contains("data"))
    {
        QJsonValue value = reply.value("data");
        bool status = value.toBool();
        if(status)
        {
            emit isDirtyTrue();
        }
        else{
            emit isDirtyFalse();
        }
    }
}
/**
 * @brief Api::failProcess 统一错误处理
 * @param reply
 */
void Api::processFailed(QNetworkReply *reply)
{
    qDebug() << "finishedSlot errors here";
    qDebug( "found error .... code: %d\n", (int)reply->error());
}
